/**
 *
 * @author ste
 */
package operazioni_database;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.sql.*;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DoQuery extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException, ClassNotFoundException, SQLException {
        doPost(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            ArrayList list = new ArrayList();
            conn = Connessione.getConnection();
            stmt = conn.createStatement();
            rs = stmt.executeQuery("SELECT * FROM anagrafica");
            while (rs.next()) {
                Persona moves = new Persona();
//                moves.setId(rs.getInt("id"));
//                moves.setNome(rs.getString("nome"));
//                moves.setCognome(rs.getString("cognome"));
                moves.setId(rs.getInt(1));
                moves.setNome(rs.getString(2));
                moves.setCognome(rs.getString(3));
                list.add(moves);
            }
            request.setAttribute("list", list);
            request.setAttribute("ResultSet", rs);
            try {
                PrintStream printS = new PrintStream(new FileOutputStream("list.txt", true));
                printS.println("new session");
                for (int j=0; j<list.size(); j++) {
                            printS.println( ((Persona)list.get(j)).getId() + " " + ((Persona)list.get(j)).getNome()
                                    + " " + ((Persona)list.get(j)).getCognome());
                }
                printS.close();
            } catch (Exception e) {
                e.getMessage();
            }



            RequestDispatcher disp = request.getRequestDispatcher("/index.jsp");
            disp.forward(request, response);
        } catch (ClassNotFoundException ex) {
            ex.getMessage();
        } catch (SQLException ex) {
            ex.getMessage();
        } finally {
            try {
                rs.close();
                stmt.close();
            } catch (SQLException ex) {
                ex.getMessage();
            }
        }
    }
}
